package com.example.sanguogameserver.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.sanguogameserver.entity.Player;
import com.example.sanguogameserver.entity.Server;
import com.example.sanguogameserver.mapper.ServerMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sanguogameserver.response.ServerRegion;
import com.example.sanguogameserver.response.ServerUserRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-03-05
 */
@Service
public class ServerService extends ServiceImpl<ServerMapper, Server> implements IService<Server> {
    @Autowired
    private PlayerService playerService;

    public ServerUserRes list(Integer userId) {
        ServerUserRes serverUserRes = new ServerUserRes();

        // 所有服务器
        List<Server> serverList = list();
        Map<String, List<Server>> regionServerMap = serverList.stream()
                .collect(Collectors.groupingBy(Server::getRegion));

        List<ServerRegion> serverRegions = new ArrayList<>(regionServerMap.size());
        for (String key : regionServerMap.keySet()) {
            ServerRegion serverRegion = new ServerRegion();
            serverRegion.setRegionServer(key);
            serverRegion.setServers(regionServerMap.get(key));
            serverRegions.add(serverRegion);
        }


        serverUserRes.setServerRegions(serverRegions);

        // 已经拥有的服务器
        List<Server> userServer = new ArrayList<>();
        List<Player> players = playerService.getByUser(userId);
        List<Integer> playerServerId = players.stream().map(Player::getServerId).collect(Collectors.toList());

        for (Server server : serverList) {
            if (playerServerId.contains(server.getId())) {
                userServer.add(server);
            }
        }
        serverUserRes.setUserServer(userServer);
        return serverUserRes;
    }
}
